package myJs.user.workflow.featureSelection

import cats.effect.SyncIO
import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react._
import japgolly.scalajs.react.util.EffectCatsEffect._
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.api.Api
import myJs.cps.BootstrapTableCp._
import myJs.cps._
import myJs.myPkg.Hooks._
import myJs.tool.Pojo._
import myJs.tool.Tool
import myJs.tool.Tool.messages
import shared.Pojo.VarInfoDataKind
import shared.pojo.VarInfoFileData
import shared.pojo.VarInfoFileData.GetAll
import upickle.default._

import scala.collection.immutable.SeqMap
import scala.scalajs.js.Dynamic.{global => g}

/**
 * Created by yz on 21/1/2022
 */
object VarInfoCp {

  case class Props(
                    fileSelect: String => SyncIO[Unit],
                    request:VarInfoFileData.GetAll.Request
                  ){
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>

    val (datas, setDatas) = useState(List.empty[ujson.Obj])
    val (columns, setColumns) = useState(List.empty[Column])

    object FTool {

      def refreshTable = {
        refreshTableB
      }

      def refreshTableB = {
        Api.varInfoFileData.getAll(props.request).flatMapSync { response =>
          val map = SeqMap("fileName" -> messages("fileName"), "tags" -> messages("tag"),
                "comment" -> messages("comment"), "size" -> messages("size"),
                "uploadTime" -> messages("uploadModifyTime"))
          val basicColumns = map.map { case (k, v) =>
            val searchKind = v match {
              case _ => TextSearch
            }
            val title = v
            val fmt = FTool.tbFmt(k)
            val comVF = FTool.comVFmt(v)
            Column(field = k, title = title, operable = true, searchKind = searchKind, formatter = fmt, comVF = comVF)
          }.toList
          val operateColumn = Column(field = "operate", title = s"${messages("operations")}",
            formatter = FTool.operateFmt, comVF = FTool.comVFmt(""))
          val columns = basicColumns :+ operateColumn
          val curDatas = response
          val datas = curDatas.map(x => writeJs(x).transform(reader[ujson.Obj]))
          setColumns(columns) >>
          setDatas(datas)
        }
      }

      def fileSelect(curFileName: String) = {
        props.fileSelect(curFileName)
      }

      def operateFmt = (v: ujson.Value, row: ujson.Obj) => {
        val folder = VarInfoDataKind.showDirName
        val curFileName = s"${folder}/${row("fileName").str}"
        button(className := "btn  green btn-xs", title := s"${messages("select")}", `type` := "button",
          onClick --> FTool.fileSelect(curFileName), s"${messages("select")}")()
      }

      def tbFmt(field: String) = (v: ujson.Value, row: ujson.Obj) => {
        field match {
          case "fileName" =>
            val url = g.jsRoutes.controllers.DataController.detailBefore().url.toString
            a(href := s"${url}?id=${row("id").num}", target := "_blank",
              s"${v.str}")()
          case "size" => span(Tool.getFileSize(v.myStr))()
          case "tags" => val tags = Tool.tagMap.getOrElse(v.myStr, v.myStr)
            span(tags)()
          case _ => span(v.myStr)()
        }
      }

      def comVFmt(fileTitle: String) = (v: ujson.Value, row: ujson.Obj) => {
        fileTitle match {
          case _ => v.myStr
        }
      }

    }

    useEffect({
      FTool.refreshTableB
    }, List()
    )

    Fragment(
      div(marginBottom := "15px",
        a(`type` := "button", className := "btn btn-primary", href := "", target := "_blank", href := s"${Api.data.baseUrl}/manageBefore",
          i(className := "fa fa-cloud-upload", s" ${messages("upload")}")
        )," ",
        a(`type` := "button", className := "btn btn-primary", onClick --> FTool.refreshTable,
          i(className := "fa fa-refresh", s" ${messages("refresh")}")
        )
      ),
      BootstrapTableCp.Props(columns = columns, datas = datas, pageList = List("5", "10", "25", "50"), pageSize = "10",
        showExport = false).render
    )

  }


}
